package com.study.talk.ui.app.common

import android.annotation.SuppressLint
import android.app.Service
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Binder
import android.os.IBinder
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.view.WindowManager.LayoutParams
import android.widget.EditText
import android.widget.TextView
import com.study.talk.R

class FloatViewService : Service() {

    private val manager by lazy { getSystemService(WINDOW_SERVICE) as WindowManager }

    private var floatView: View? = null

    private var contentView: TextView? = null
    private var aiChatBt: TextView? = null
    private var aiChatEdit: EditText? = null

    abstract class FloatViewBinder : Binder() {
        abstract fun addContent(content: String)
        abstract fun show()
        abstract fun dismiss()
    }

    override fun onBind(intent: Intent): IBinder {
        return object : FloatViewBinder() {
            @SuppressLint("SetTextI18n")
            override fun addContent(content: String) {
                contentView?.text = contentView?.text.toString() + content
            }

            override fun show() {
                showFloatView()
            }

            override fun dismiss() {
                removeFloatView()
            }
        }
    }

    private fun showFloatView() {
        floatView = LayoutInflater.from(this).inflate(R.layout.smart_chat, null)
        floatView?.let {
            initView(it)
            //设置浮窗参数
            val params = LayoutParams(
                LayoutParams.TYPE_APPLICATION_OVERLAY,
                LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT
            ).apply {
                width = LayoutParams.MATCH_PARENT
                height = LayoutParams.MATCH_PARENT
            }
            manager.addView(it,params)
        }
    }

    private fun initView(view: View) {
        contentView = view.findViewById(R.id.ai_chat_content)
        aiChatBt = view.findViewById(R.id.ai_chat_msg_send_bt)
        aiChatEdit = view.findViewById(R.id.ai_chat_msg_edit)
        aiChatBt?.setOnClickListener { _ ->
            removeFloatView()
        }
    }

    override fun onDestroy() {
        removeFloatView()
        super.onDestroy()
    }

    private fun removeFloatView(){
        floatView?.let {
            manager.removeView(floatView)
        }
        floatView  = null
    }
}